package com.polaris.live.ui.party.music

import android.os.Bundle
import android.text.Editable
import android.view.View
import androidx.recyclerview.widget.LinearLayoutManager
import com.blankj.utilcode.util.KeyboardUtils
import com.blankj.utilcode.util.StringUtils
import com.bumptech.glide.Glide
import com.bumptech.glide.load.resource.bitmap.CenterCrop
import com.bumptech.glide.load.resource.bitmap.RoundedCorners
import com.polaris.live.R
import com.polaris.live.adapter.music.MusicMainItemAdapter
import com.polaris.live.cache.CommonCache
import com.polaris.live.common.ext.autoDp
import com.polaris.live.common.ext.setOnSingleClickListener
import com.polaris.live.common.mvvm.base2.BaseVbFragment
import com.polaris.live.common.mvvm.viewmodel.BaseViewModel
import com.polaris.live.databinding.FragmentMusicMainBinding
import com.polaris.live.interface_bag.TextWatcherAdapter
import com.polaris.live.popup.MusicVolumePopup
import com.polaris.live.popup.PublicTipsPopup
import com.polaris.live.resp.event.MusicUpSeatEvent
import com.polaris.live.translation.R.*
import com.polaris.live.ui.party.PartyUserStateUtil
import com.polaris.live.ui.party.music.listener.MediaPlayerPlayingListener
import com.polaris.live.ui.party.music.listener.MusicMainListener
import com.polaris.live.utils.zego.media.MediaProxy
import com.polaris.live.utils.zego.media.MusicBean
import com.polaris.live.utils.zego.media.MusicPlay
import com.polaris.live.utils.zego.media.MusicState
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode

/**
 * MusicMianFragment 主页面
 *
 * @author Created by 天晴 on 2024/9/14 17:26
 * @since 1.0.0
 **/
class MusicMainFragment : BaseVbFragment<BaseViewModel, FragmentMusicMainBinding>(), MediaPlayerPlayingListener {

    var listener: MusicMainListener? = null
    private val emptyView by lazy {
        EmptyMusicView(requireContext()).apply {
            setEmptyTip(
                R.drawable.salalogo,
                StringUtils.getString(string.no_music),
                width = 40.autoDp,
                height = 40.autoDp,
            )
        }
    }
    private val mAdapter by lazy { MusicMainItemAdapter() }

    private var tempMusic: MusicBean? = null //临时点击等待播放的条目
    override fun initView(savedInstanceState: Bundle?) {
        EventBus.getDefault().register(this)

        mBinding.apply {
            recycler.apply {
                itemAnimator = null
                layoutManager = LinearLayoutManager(context)
                adapter = mAdapter
            }

            when (MediaProxy.getMusicPlayType()) {
                MusicPlay.MUSIC_SINGLE -> {
                    musicType.setImageResource(R.drawable.music_single)
                }

                MusicPlay.MUSIC_RANDOM -> {
                    musicType.setImageResource(R.drawable.music_random)
                }

                MusicPlay.MUSIC_ORDER -> {
                    musicType.setImageResource(R.drawable.music_order)
                }
            }
            setTitle()

            tipsLl.visibility = if (CommonCache.getMusicTipsClose()) View.GONE else View.VISIBLE
        }
        mAdapter.setEmptyView(emptyView)

        initObserve()
        initListener()

        setData()

        MediaProxy.getCurrentMusicBean()?.let {
            setCurrentMusic(it)
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onMusicUpSeat(event: MusicUpSeatEvent) {
        tempMusic?.let {
            MediaProxy.startMusic(it)
        }
    }

    private fun setTitle() {
        mBinding.titleTv.text = "${StringUtils.getString(string.my_music)}(${MediaProxy.getMusicList().size})"
    }

    private fun setCurrentMusic(currentMusic: MusicBean) {
        mBinding.apply {
            musicName.text = currentMusic.name
            totalTime.text = formatTime(currentMusic.duration)
            mBinding.musicProgress.setMax(currentMusic.duration.toInt())
            val p = MediaProxy.getCurrentMusicProgress()
            mBinding.musicProgress.setProgress(p.toInt())
            mBinding.playTime.text = formatTime(p)
            val volume = MediaProxy.getPlayVolume()
            if (volume > 0) {
                mBinding.musicVolume.setImageResource(R.drawable.music_volume)
            } else {
                mBinding.musicVolume.setImageResource(R.drawable.music_volume_close)
            }
            Glide.with(requireContext())
                .load(currentMusic.getAlbumCoverFromMusicFile())
                .placeholder(R.drawable.unknown_cover)
                .error(R.drawable.unknown_cover)
                .transform(CenterCrop(), RoundedCorners(6.autoDp))
                .into(musicPlayerCover)
        }
    }

    private fun formatTime(millis: Long): String {
        val seconds = millis / 1000
        val hours = seconds / 3600
        val minutes = (seconds % 3600) / 60
        val secs = seconds % 60

        return when {
            hours > 0 -> String.format("%02d:%02d:%02d", hours, minutes, secs)
            minutes > 0 -> String.format("%02d:%02d", minutes, secs)
            else -> String.format("00:%02d", secs)
        }
    }

    fun setData() {
        mAdapter.setList(MediaProxy.getMusicList())
        MediaProxy.getCurrentMusicBean()?.let {
            mAdapter.switchMusic(it)
            mAdapter.musicState(MediaProxy.getCurrentMusicState())
        }
    }

    private fun initListener() {
        MediaProxy.addListener(this)
        mBinding.closeTips.setOnSingleClickListener {
            mBinding.tipsLl.visibility = View.GONE
            CommonCache.saveMusicTipsClose(true)
        }
        mBinding.addBtn.setOnSingleClickListener {
            listener?.toAdd()
        }
        mBinding.close.setOnSingleClickListener {
            listener?.close()
        }
        emptyView.setOnSingleClickListener {
            listener?.toAdd()
        }
        mBinding.musicVolume.setOnSingleClickListener {
            MusicVolumePopup.show(requireContext(), mBinding.musicVolume)
        }
        mBinding.musicType.setOnClickListener {
            MediaProxy.chickMusicPlayType()
        }
        mBinding.musicProgress.setSeekToProgress {
            MediaProxy.seekTo(it)
        }
        mBinding.clearImg.setOnSingleClickListener {
            mBinding.editText.setText("")
        }
        mBinding.editText.setOnClickListener {
            if (!mBinding.editText.hasFocus()) {
                mBinding.editText.requestFocus()
            }
            KeyboardUtils.showSoftInput()
        }
        mAdapter.setOnItemChildClickListener { _, view, position ->
            val item = mAdapter.getItem(position)
            val currentIndex = mAdapter.getCurrentIndex()
            when (view.id) {
                R.id.music_rm -> {
                    mAdapter.removeAt(position)
                    MediaProxy.rmMusicList(item)
                }

                R.id.music_play -> {
                    if (!PartyUserStateUtil.inTheMaiSeat) { //不在麦位
                        PublicTipsPopup.show(
                            requireContext(), this,
                            StringUtils.getString(string.prompt),
                            StringUtils.getString(string.you_not_seated_room),
                            StringUtils.getString(string.go_sit_down),
                            StringUtils.getString(string.close),
                            isViewMode = false,
                            onTop = {
                                tempMusic = item
                                listener?.toUpSeat()
                            })
                        return@setOnItemChildClickListener
                    } else if (PartyUserStateUtil.siteMicStatus == 2) {
                        PublicTipsPopup.show(
                            requireContext(), this,
                            StringUtils.getString(string.prompt),
                            StringUtils.getString(string.you_banned_playing_music),
                            "",
                            StringUtils.getString(string.close),
                            showTop = false,
                            isViewMode = false,
                            onTop = {
                                listener?.close()
                            }
                        )
                        return@setOnItemChildClickListener
                    }
                    if (currentIndex != position) {
                        MediaProxy.startMusic(item)
                    } else {
                        when (MediaProxy.getCurrentMusicState()) {
                            MusicState.UNREADY,
                            MusicState.READY,
                            MusicState.PLAY_ENDED,
                            MusicState.STOPING,
                            MusicState.FAIL,
                                -> {
                                MediaProxy.retryMusic(item)
                            }

                            MusicState.PLAYING -> {
                                MediaProxy.pause()
                            }

                            MusicState.PAUSE -> {
                                MediaProxy.startMusic(item)
                            }
                        }
                    }
                }
            }
        }
    }

    private fun initObserve() {
        mBinding.editText.addTextChangedListener(object : TextWatcherAdapter() {
            override fun afterTextChanged(s: Editable?) {
                val str = s?.toString()
                if (str.isNullOrEmpty()) {
                    mBinding.clearImg.visibility = View.GONE
                    setData()
                } else {
                    mBinding.clearImg.visibility = View.VISIBLE
                    val newList = MediaProxy.getMusicList().filter { it.name.contains(str) || it.artist.contains(str) }
                    mAdapter.setList(newList)
                }
            }
        })
    }

    fun search() {

    }

    fun setMusicMainListener(listener: MusicMainListener) {
        this.listener = listener
    }

    override fun onDestroyView() {
        super.onDestroyView()
        MediaProxy.rmListener(this)
        EventBus.getDefault().unregister(this)
    }

    /**
     * 播放器控制======================================
     */
    override fun progress(millisecond: Long) {
        mBinding.musicProgress.setProgress(millisecond.toInt())
        mBinding.playTime.text = formatTime(millisecond)
    }

    override fun switchMusic(music: MusicBean) {
        mAdapter.switchMusic(music)
        setCurrentMusic(music)
    }

    override fun musicState(state: Int) {
        mAdapter.musicState(state)

    }

    override fun musicPlayType(type: Int) {
        when (type) {
            MusicPlay.MUSIC_SINGLE -> {
                mBinding.musicType.setImageResource(R.drawable.music_single)
            }

            MusicPlay.MUSIC_RANDOM -> {
                mBinding.musicType.setImageResource(R.drawable.music_random)
            }

            MusicPlay.MUSIC_ORDER -> {
                mBinding.musicType.setImageResource(R.drawable.music_order)
            }
        }
    }

    override fun onVolumeUpdate(volume: Int) {
        if (volume > 0) {
            mBinding.musicVolume.setImageResource(R.drawable.music_volume)
        } else {
            mBinding.musicVolume.setImageResource(R.drawable.music_volume_close)
        }
    }

    override fun onMusicSizeUpdate(size: Int) {
        setTitle()
    }
}